package com.lxq.web.servlet.mng;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.lxq.common.DaoFactory;
import com.lxq.dao.CardDao;
import com.lxq.entity.Card;
import com.lxq.web.servlet.common.BaseServlet;

@WebServlet("/app/mng/card")
public class CardServlet extends BaseServlet {
	private static final long serialVersionUID = 3064552888186701776L;
	private CardDao cardDao = DaoFactory.getInstance("cardDao", CardDao.class);

	@Override
	public void doUpdate(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		String cardnumber = request.getParameter("cardnumber");
		String currentbalance = request.getParameter("currentbalance");
		String state = request.getParameter("state");

		Card card = cardDao.findByCardNumber(cardnumber);
		JSONObject json = new JSONObject();

		try {
			if (card != null) {
				if (currentbalance != null && state == null) { // 执行余额更新

					Integer balance = new Integer(card.getCurrentBalance());
					balance = balance + new Integer(currentbalance);
					cardDao.updateCurrentBalance(cardnumber, balance.toString());

					json.put("success", true);

				} else if (currentbalance == null && state != null) { // 执行状态更新
					cardDao.updateCardState(cardnumber, Integer.valueOf(state).intValue());
					json.put("success", true);
				}
			} else {
				json.put("success", false);
				json.put("reason", "卡不存在！");
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().print(json.toString());
		response.getWriter().flush();
	}

	@Override
	public void doFindOne(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		String cardnumber = request.getParameter("cardnumber");

		Card card = cardDao.findByCardNumber(cardnumber);
		JSONObject json = new JSONObject();

		try {
			if (card != null) {
				
				json.put("success", true);
				json.put("cards", new JSONObject(card));
				
			} else {
				json.put("success", false);
				json.put("reason", "卡不存在！");
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().print(json.toString());
		response.getWriter().flush();
	}
}
